import express from "express";
import { createServer } from "http";
import { Server } from "socket.io";
import path from "path";

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
  cors: {
    origin: "http://localhost:5173",
    methods: ["GET", "POST"],
  },
});

// 游戏房间状态
const rooms = new Map();

io.on("connection", (socket) => {
  console.log("用户连接:", socket.id);

  // 创建或加入房间
  socket.on("joinRoom", (roomId) => {
    socket.join(roomId);

    if (!rooms.has(roomId)) {
      rooms.set(roomId, {
        players: new Set(),
        puzzleState: null,
        image: null,
        difficulty: 3,
      });
    }

    const room = rooms.get(roomId);
    room.players.add(socket.id);

    // 发送房间信息给新加入的玩家
    socket.emit("roomState", {
      players: Array.from(room.players),
      puzzleState: room.puzzleState,
      image: room.image,
      difficulty: room.difficulty,
    });

    // 通知房间其他玩家有新玩家加入
    socket.to(roomId).emit("playerJoined", socket.id);
  });

  // 更新拼图状态
  socket.on("updatePuzzle", ({ roomId, puzzleState, image, difficulty }) => {
    const room = rooms.get(roomId);
    if (room) {
      room.puzzleState = puzzleState;
      room.image = image;
      room.difficulty = difficulty;
      socket
        .to(roomId)
        .emit("puzzleUpdated", { puzzleState, image, difficulty });
    }
  });

  // 移动拼图块
  socket.on("movePiece", ({ roomId, pieceId, targetIndex }) => {
    socket.to(roomId).emit("pieceMoved", { pieceId, targetIndex });
  });

  // 断开连接
  socket.on("disconnect", () => {
    console.log("用户断开连接:", socket.id);
    // 从所有房间中移除玩家
    rooms.forEach((room, roomId) => {
      if (room.players.has(socket.id)) {
        room.players.delete(socket.id);
        io.to(roomId).emit("playerLeft", socket.id);

        // 如果房间空了，删除房间
        if (room.players.size === 0) {
          rooms.delete(roomId);
        }
      }
    });
  });
});

const PORT = process.env.PORT || 3000;
httpServer.listen(PORT, () => {
  console.log("Server running on port " + PORT);
});
